import { login, logout, getInfo } from '@/api/auth'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  title: '',
  academy: '',
  avatar: '',
  area: null,
  area_id: 0,
  roles: []
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_TITLE: (state, name) => {
    state.title = name
  },
  SET_ACADEMY: (state, name) => {
    state.academy = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar || ''
  },
  SET_AREA: (state, area) => {
    state.area = area || null
  },
  SET_AREA_ID: (state, area) => {
    state.area_id = area || 0
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ account: username.trim(), password: password }).then(response => {
        commit('SET_TOKEN', response.access_token)
        setToken(response.access_token)
        console.log(response)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const data = response

        if (!data) {
          reject('Verification failed, please Login again.')
        }

        const { name, avatar, rank_readable, academy, permissions, area, area_id } = data

        commit('SET_NAME', name)
        commit('SET_AVATAR', avatar)
        commit('SET_TITLE', rank_readable)
        commit('SET_ACADEMY', academy)
        commit('SET_ROLES', permissions)
        commit('SET_AREA', area)
        commit('SET_AREA_ID', area_id)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

